package com.mgq.netty.simpleNettyServer;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        //1.启动类
        ChannelFuture channelFuture = new Bootstrap()
                //2.添加EventLoop
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override //在连接建立后被调用
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8088));
        //直到连接建立
        //方式一,主线程等待
       /* ChannelFuture future = channelFuture.sync();
        //代表连接对象
        Channel channel = future.channel();
        log.debug("channel:{}",channel);
        channel.writeAndFlush("hello world");*/

        //方式二:交给其他线程处理
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            //操作完成时调用
            public void operationComplete(ChannelFuture future) throws Exception {
                Channel channel = future.channel();
                log.debug("channel:{}",channel);
                channel.writeAndFlush("hello world");
            }
        });
    }
}
